import { defineStore } from 'pinia'
import { UserState } from '../types'
import store from '../pinia'
import { StorageSerializers } from '@vueuse/core'
import { nextTick } from 'vue'
import { useRole } from '@/views/system/role.hook'

const useUserStore = defineStore('user-info', () => {

  const { RoleId } = useRole()

  const info = useLocalStorage<UserState | undefined>('userInfo', null, {
    serializer: StorageSerializers.object
  })

  const isAdmin = computed(() => info.value?.userRole == RoleId.Admin)
  const isManager = computed(() => info.value?.userRole == RoleId.Manager)
  const isFinance = computed(() => info.value?.userRole == RoleId.Finance)

  const isTokenExpire = computed(() => !info.value)

  const saveUser = (userInfo: UserState) => new Promise<UserState>((resolve) => {
    info.value = userInfo
    resolve(userInfo)
  })

  const logout = () => new Promise<void>((resolve) => {
    console.log('logged out')
    delete info.value
    localStorage.clear()
    sessionStorage.clear()
    resolve()
  }).finally(() => document.dispatchEvent(new CustomEvent('logout')))


  return {
    info,

    isTokenExpire,
    isAdmin,
    isManager,
    isFinance,

    saveUser,
    logout,
  }
})

export default useUserStore

/**
 * 返回一个Promise对象，目的是防止在非vue组件使用中的时候出现插件还没有出初始化完成导致持久化操作失败的bug。
 * 使用方式：
 *  import { useUserStoreContext } from '@/store/modules/user'
    useUserStoreContext().then((store) => {
      console.log(store.nickName)
    })
 * @returns Promise<typeof useUserStore>
 */
export async function useUserStoreContext() {
  await nextTick()
  return useUserStore(store)
}
